package com.crowdfunding.controller;

import com.crowdfunding.bean.*;
import com.crowdfunding.listener.PassListener;
import com.crowdfunding.listener.RefuseListener;
import com.crowdfunding.service.*;
import com.crowdfunding.util.Const;
import com.crowdfunding.vo.Data;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@Controller
@RequestMapping("/member")
public class MemberController extends BaseController{
    @Autowired
    private TicketService ticketService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private CertService certService;
    @Autowired
    private MemberCertService memberCertService;
    @Autowired
    private RepositoryService repositoryService ;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @RequestMapping("/accttype")
    public String accttype(){
        return "member/accttype";
    }
    @RequestMapping("/basicinfo")
    public String basicinfo(){
        return "member/basicinfo";
    }

    @RequestMapping("/uploadCert")
    public String uploadCert(){
        return "member/uploadCert";
    }
    @RequestMapping("/checkemail")
    public String checkemail(){
        return "member/checkemail";
    }

    @RequestMapping("/checkauthcode")
    public String checkauthcode(){
        return "member/checkauthcode";
    }

    @RequestMapping("/apply")
    public String apply(HttpSession session){
        Member loginMember = (Member)session.getAttribute(Const.LOGIN_MEMBER);

            Ticket ticket=ticketService.getTicketByMemberId(loginMember.getId());
            if(null==ticket){
                ticket=new Ticket();
                ticket.setMemberid(loginMember.getId());
                ticket.setPstep("apply");
                ticket.setStatus("0");
                Integer count=ticketService.saveTicket(ticket);

            }else{
                String pstep=ticket.getPstep();
                if("accttype".equals(pstep)){
                    return "redirect:/member/basicinfo.htm";
                }else if("basicinfo".equals(pstep)){
                    String accttype = loginMember.getAccttype();
                    List<Cert> queryCertByAccttype=certService.queryCertByAccttype(accttype);
                    session.setAttribute("queryCertByAccttype",queryCertByAccttype);
                    return "redirect:/member/uploadCert.htm";
                }else if("uploadcert".equals(pstep)){
                    String accttype = loginMember.getAccttype();
                    List<Cert> queryCertByAccttype=certService.queryCertByAccttype(accttype);
                    session.setAttribute("queryCertByAccttype",queryCertByAccttype);
                    return "redirect:/member/checkemail.htm";
                }else if("checkemail".equals(pstep)){
                    return "redirect:/member/checkauthcode.htm";
                }
            }
            return "member/accttype";

    }
    @RequestMapping("/updateBaticinfo")
    @ResponseBody
    public Object updateBaticinfo(Member member, HttpSession session){
        start();
        try{
            Member loginMember= (Member)session.getAttribute(Const.LOGIN_MEMBER);
            loginMember.setCardnum(member.getCardnum());
            loginMember.setRealname(member.getRealname());
            loginMember.setTel(member.getTel());
            Integer count=memberService.updateBaticinfo(loginMember);
            Ticket ticket=ticketService.getTicketByMemberId(loginMember.getId());
            ticket.setPstep("basicinfo");
            ticketService.updatePstep(ticket);
            success(count==1);
        }catch (Exception e){
            success(false);
            message("账户类型更新出错！");
            e.printStackTrace();
        }
        return end();
    }

    @RequestMapping("/updateAcctType")
    @ResponseBody
    public Object updateAcctType(String accttype, HttpSession session){
        start();
        try{
            Member member= (Member)session.getAttribute(Const.LOGIN_MEMBER);
            member.setAccttype(accttype);
            //更新账户类型
            Integer count=memberService.updateAcctType(member);
            //记录步骤流程
            Ticket ticket=ticketService.getTicketByMemberId(member.getId());
            ticket.setPstep("accttype");
            ticketService.updatePstep(ticket);
            success(count==1);
            session.setAttribute(Const.LOGIN_MEMBER,member);
        }catch (Exception e){
            success(false);
            message("账户类型更新出错！");
            e.printStackTrace();
        }
        return end();
    }
    @RequestMapping("/doUploadCert")
    @ResponseBody
    public Object doUploadCert(Data data, HttpSession session){
        start();
        try{
            //获取登录会员信息
            Member loginMember=(Member)session.getAttribute(Const.LOGIN_MEMBER);
            List<MemberCert> certimg = data.getCertimgs();
            String realPath = session.getServletContext().getRealPath("/picture");

            for (MemberCert memberCert :
                    certimg) {
                //资质文件上传
                MultipartFile file = memberCert.getFile();
                String originalFilename = file.getOriginalFilename();
                String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
                String filename=UUID.randomUUID().toString()+ext;
                String filepath=realPath+"/cert"+"/"+ filename;
                file.transferTo(new File(filepath));
                memberCert.setIconpath(filename);
                memberCert.setMemberid(loginMember.getId());
            }
            int count=memberCertService.saveMemberCert(certimg);

            //记录流程步骤
            Ticket ticket=ticketService.getTicketByMemberId(loginMember.getId());
            ticket.setPstep("uploadcert");
            ticketService.updatePstep(ticket);
            success(true);
        }catch (Exception e){
            success(false);
            message("账户类型更新出错！");
            e.printStackTrace();
        }
        return end();
    }
    @RequestMapping("startProcess")
    @ResponseBody
    public Object startProcess(String email,HttpSession session){
        start();
        try{
            //更新会员的邮箱
            Member loginMember=(Member)session.getAttribute(Const.LOGIN_MEMBER);
            if (!loginMember.getEmail().equals(email)){
                loginMember.setEmail(email);
                int count=memberService.updateEmail(loginMember);
            }
            //开始邮箱流程
            //启动流程定义
            ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().processDefinitionKey("auth").latestVersion().singleResult();
            Map<String,Object>param=new HashMap<>();
            Integer authcode=(int)((Math.random()*9+1)*1000);//随机4位验证码

            param.put("toEmail",email);
            param.put("loginacct",loginMember.getLoginacct());
            param.put("authcode",authcode);
            //流程监听执行操作
            param.put("passListener",new PassListener());
            param.put("refuseListener",new RefuseListener());
            //启动流程实例
            ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId(), param);
            //记录当前的步骤
            Ticket ticket=ticketService.getTicketByMemberId(loginMember.getId());
            ticket.setPstep("checkemail");
            ticket.setPiid(processInstance.getId());
            //同时将验证码存入数据库中
            ticket.setAuthcode(authcode.toString());
            ticketService.updatePiidAndPstep(ticket);
            success(true);
        }catch (Exception e){
            e.printStackTrace();
            success(false);
            message("获取验证码出错！");
        }

        return end();
    }

    @RequestMapping("doFinishApply")
    @ResponseBody
    public Object doFinishApply(String authcode,HttpSession session){
        start();
        try{

            Member loginMember=(Member)session.getAttribute(Const.LOGIN_MEMBER);
            //更新步骤
            Ticket ticket = ticketService.getTicketByMemberId(loginMember.getId());
            if (authcode.equals(ticket.getAuthcode())){
                ticket.setPstep("finishapply");
                ticketService.updatePstep(ticket);
                //当前系统用户完成验证码审核的任务
                ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().latestVersion().singleResult();
                Task task= taskService.createTaskQuery().processInstanceId(ticket.getPiid()).taskAssignee(loginMember.getLoginacct()).singleResult();
                taskService.complete(task.getId());
                //更新用户申请状态
                loginMember.setAuthstatus("1");
                memberService.updateAuthstatus(loginMember);
                success(true);
            }else{
                success(false);
                message("验证码不正确，请重新获取验证码！");
            }

        }catch (Exception e){
            e.printStackTrace();
            success(false);
            message("效验验证码出错！");
        }

        return end();
    }
}
